﻿using System;
using RimWorld;
using Verse;
using Verse.Sound;
using UnityEngine;
using System.Collections.Generic;

namespace SZ.Mech
{
    class CompHitToActive : ThingComp
    {
        public CompProperties_HitToActive Props
        {
            get
            {
                return (CompProperties_HitToActive)this.props;
            }
        }

        public bool shouldActiveAll = true;

        public Map cachedMap;
        public IntVec3 cachedPosition;

        private Pawn cachedPawn;
        private static Stack<CompHitToActive> records = new Stack<CompHitToActive>();


        public override void PostSpawnSetup(bool respawningAfterLoad)
        {
            base.PostSpawnSetup(respawningAfterLoad);
            if (cachedPawn == null)
            {
                cachedPawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(this.Props.pawnToActive, this.parent.Faction));


                //cachedPawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(this.Props.pawnToActive, this.parent.Faction, PawnGenerationContext.NonPlayer, -1, false, false, false, false, true, false, 1f, false, true, true, true, false, false, false, false, 0f, 0f, null, 1f, null, null, null, null, null, new float?(this.Props.pawnToActive.race.race.lifeStageAges[0].minAge), null, null, null, null, null, null, null, false, false, false));
            }
            cachedMap = this.parent.Map;
            cachedPosition = this.parent.Position;
            AddRecord(this);
        }
        /// <summary>
        /// 破坏后广播触发
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="previousMap"></param>
        public override void PostDestroy(DestroyMode mode, Map previousMap)
        {
            if (shouldActiveAll)
            {
                ActiveAllInMap(this.cachedMap);
            }

            base.PostDestroy(mode, previousMap);
        }

        public void SetCachedPawn(Pawn panw)
        {
            this.cachedPawn = panw;
        }

        private void Active()
        {
            GenSpawn.Spawn(this.cachedPawn, this.cachedPosition, this.cachedMap, WipeMode.Vanish);
            if (this.Props.soundActive != null)
            {
                this.Props.soundActive.PlayOneShot(new TargetInfo(this.parent.Position, this.parent.Map, false));
            }
        }

        private static void AddRecord(CompHitToActive record)
        {
            CompHitToActive.records.Push(record);
        }

        private static void ActiveAllInMap(Map map)
        {
            while (records.Any())
            {
                CompHitToActive tmp = records.Pop();

                if (tmp.cachedMap != map) continue;
                tmp.Active();
                Log.Message(tmp.parent.Destroyed.ToString());
                if (!tmp.parent.Destroyed)
                {
                    tmp.shouldActiveAll = false;
                    tmp.parent.Destroy();
                }
            }
        }

    }
}
